<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\GroupBuyStoreRequest;
use App\Models\GroupBuy;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class GroupBuyController extends AdminBaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return JsonResponse|object
     */
    public function index()
    {
        $list = GroupBuy::filter(\request()->all())->orderByRaw('id desc')->paginate(\request('perPage', 10));
        return $this->restful($list);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param GroupBuyStoreRequest $request
     * @return JsonResponse|object
     */
    public function store(GroupBuyStoreRequest $request)
    {
        $params = $request->validated();
        $exists = GroupBuy::where('type', $params['type'])->where('data_id', $params['data_id'])->exists();
        if ($exists) return $this->restful(null, false, '当前数据已存在拼团设置');
        $model = GroupBuy::create($params);

        return $this->restful($model);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param GroupBuyStoreRequest $request
     * @param int $id
     * @return JsonResponse|object
     */
    public function update(GroupBuyStoreRequest $request, int $id)
    {
        $params = $request->validated();
        $model = GroupBuy::where('id', $id)->update(\Arr::except($params, ['data_id', 'type']));
        return $this->restful($model);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return JsonResponse|object
     */
    public function destroy($id)
    {
        $model = GroupBuy::where('id', $id)->delete();

        return $this->restful($model);
    }
}
